import time

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from BK_login.utils.log_util import logger


class Base():
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(self.driver, 20)

    # 查找单个元素
    def find_element(self, locator):
        try:
            logger.info(f"查找元素 {locator}")
            return self.wait.until(EC.visibility_of_element_located(locator))
        except Exception as e:
            logger.error(f"元素 {locator} 定位失败。失败原因是：\n {e}")

    # 查找多个元素
    def find_elements(self, locator):
        try:
            logger.info(f"查找元素 {locator}")
            return self.wait.until(EC.visibility_of_all_elements_located(locator))
        except Exception as e:
            logger.error(f"元素 {locator} 定位失败。失败原因是：\n {e}")

    # 输入数据
    def input_data(self, locator, keywords):
        # 查找元素
        element = self.find_element(locator)
        # 清空输入框的内容
        element.clear()
        # 输入数据
        logger.info(f"输入数据: {keywords}")
        element.send_keys(keywords)

    def clickBtn(self, locator):
        # 查找元素
        button = self.find_element(locator)
        # 点击按钮
        logger.info(f"点击按钮: {locator}")
        button.click()
        time.sleep(0.5)

    def switchAlert(self, keywords=None, text=True, action=True):
        try:
            # 切换到警告框
            alert = self.driver.switch_to.alert
            # 如果客户传入了数据，就输入数据
            if keywords:
                alert.send_keys(keywords)
            # 获取文本信息
            if text:
                text = alert.text
            # 点击确认按钮
            if action:
                alert.accept()
            else:
                # 点击取消按钮
                alert.dismiss()
            # 返回文本信息
            if text:
                logger.info(f"返回文本信息：{text}")
                return text
        except Exception as e:
            logger.error(f"警告框的操作失败，错误信息是：\n{e}")

    # 获取元素的文本信息
    def get_text(self, locator):
        # 查找元素
        element = self.find_element(locator)
        # 获取文本信息
        text = element.text
        logger.info(f"查找元素 {locator}")(f"获取到的文本信息是：{text}")
        return text


